const bcrypt = require('bcryptjs')
const fs = require('fs')
const toPdf = require('office-to-pdf')
const debug = require('debug')('tools')
const db = require('./db.js')
const pdf = require('pdf-page-counter')
const jwt = require('jsonwebtoken')

const ConfigManager = require('../lib/config')
const urllist = {}
let flag = 0

function Tool () {
}

Tool.prototype = {
  constructor: Tool,

  deleteFile: function (filelist, callback) {
    console.log(filelist)
    for (var i = 0; i < filelist.length; i++) {
      fs.unlink(filelist[i], function (err) {
        if (err) {
          throw err
        }
        console.log('成功删除了文件')
        return callback()
      })
    }
  },

  createJson: function (prop, val) {
    // 如果 val 被忽略
    if (typeof val === 'undefined') {
      // 删除属性
      return delete urllist[prop]
    }
    // 添加 或 修改
    urllist[prop] = val
    return urllist
  },

  // 密码加密函数
  enbcrypt: function (password) {
    const salt = bcrypt.genSaltSync(10)
    const hash = bcrypt.hashSync(password, salt)
    return hash
  },

  getname: function () {
    const basename = parseInt(Math.random() * 100) + Date.now().toString()
    return basename
  },

  vetify: function (token, callback) {
    if (token) {
      jwt.verify(token, ConfigManager.getSecretKey(), (err, decoded) => {
        if (err) {
          const msg = { code: 0, message: 'token无效', userinfo: decoded }
          callback(msg)
        } else {
          const msg = { code: 1, message: 'token有效', userinfo: decoded }
          callback(msg)
        }
      })
    }
  },

  ifPdf: function (file, pdfPath, callback) {
    // 创建可读流
    const reader = fs.createReadStream(file.path)
    // 创建可写流
    const upStream = fs.createWriteStream(pdfPath)
    // 可读流通过管道写入可写流
    reader.pipe(upStream)
    reader.on('end', () => {
      debug('文件保存完成')
      callback()
    })
  },

  noPdf: function (file, filePath, callback) {
    // 创建可读流
    const reader = fs.createReadStream(file.path)
    // 创建可写流
    const upStream = fs.createWriteStream(filePath)
    // 可读流通过管道写入可写流
    reader.pipe(upStream)
    reader.on('end', () => {
      debug('文件保存完成')
      callback()
    })
  },

  WordtoPdf: function (filePath, pdfPath, callback) {
    fs.readFile(filePath, function (err, result) {
      if (err) {
        return debug(err)
      }
      if (result.length > 0) {
        toPdf(result).then(
          (pdfBuffer) => {
            fs.writeFileSync(pdfPath, pdfBuffer)
            debug('成功生成PDF文件')
            return callback()
          }, (err) => {
            return debug('转化失败', err)
          }
        )
      }
    })
  },

  getnumpages: async function (pdfPath, callback) {
    // 获取页数
    const dataBuffer = await fs.readFileSync(pdfPath)
    pdf(dataBuffer).then(function (data) {
      const numpages = data.numpages
      return callback(numpages)
    })
  },

  setflag: function (flag1) {
    flag = flag1
  },

  getflag: function () {
    return flag
  },

  print: function (jobUuid, fileUuid, bid, deviceid) {
    const printUrl = ConfigManager.getprintUrl()
    // debug(fileUrl)
    const rpOptions = {
      method: 'POST',
      uri: printUrl,
      headers: {
        Accept: 'application/json'
      },
      resolveWithFullResponse: false,
      body: {
        action: 'startup', // 行为，固定，必填
        rules: 'immediately', // 运行规则，固定，必填
        node_sn: [bid],
        parameters: {
          msgId: jobUuid, // 随机生成的 uuid 作为后续返回的凭证
          callbackUrl: 'https://print.net-frog.com/api/print/printStatus', // 打印结果回调地址，可选
          // callbackUrl: 'http://10.22.75.241:3000/api/print/printStatus', // 打印结果回调地址，可选
          fileUrl: 'https://print.net-frog.com/pdf/' + fileUuid + '.pdf' // 文件地址，必填
          // fileUrl: 'http://10.22.75.241:3000/pdf/' + fileUuid + '.pdf' // 文件地址，必填
          // deviceId: deviceid // 打印机唯一值，必填
          // copies: 1,//打印份数，可选，默认为 1
          // page-list: "1,3-5,16" //打印页数，可选，默认为整份打印
        }
      },
      json: true
    }
    return rpOptions
  },

  getAdminList: async function (currentPage, pageSize) {
    if (currentPage === 1) {
      var page = 0
    } else {
      page = currentPage * pageSize - pageSize
    }
    const adminlist = await db.findAdminUser(page, pageSize)
    const adminCounts = await db.findAdminCount()
    const adminCount = adminCounts[0].num
    const currentPages = currentPage
    const option = {
      adminlist: adminlist,
      currentPage: currentPages,
      admintotalPages: Math.ceil(adminCount / pageSize)
    }
    return option
  },

  getUserList: async function (currentPage, pageSize) {
    if (currentPage === 1) {
      var page = 0
    } else {
      page = currentPage * pageSize - pageSize
    }
    const userlist = await db.findUser(page, pageSize)
    const userCounts = await db.findUserCount()
    const userCount = userCounts[0].num
    const currentPages = currentPage
    const option = {
      userlist: userlist,
      currentPage: currentPages,
      usertotalPages: Math.ceil(userCount / pageSize)
    }
    return option
  },

  getFileList: async function (currentPage, pageSize) {
    if (currentPage === 1) {
      var page = 0
    } else {
      page = currentPage * pageSize - pageSize
    }
    const filelist = await db.findFile(page, pageSize)
    const fileCounts = await db.findFileCount()
    const fileCount = fileCounts[0].num
    const currentPages = currentPage
    const option = {
      filelist: filelist,
      currentPage: currentPages,
      filetotalPages: Math.ceil(fileCount / pageSize)
    }
    return option
  },

  getPrintList: async function (currentPage, pageSize) {
    if (currentPage === 1) {
      var page = 0
    } else {
      page = currentPage * pageSize - pageSize
    }
    const printlist = await db.findPrints(page, pageSize)
    const printCounts = await db.findPrintCount()
    const printCount = printCounts[0].num
    const currentPages = currentPage
    const option = {
      printlist: printlist,
      currentPage: currentPages,
      printtotalPages: Math.ceil(printCount / pageSize)
    }
    return option
  },

  getRecordList: async function (currentPage, pageSize) {
    if (currentPage === 1) {
      var page = 0
    } else {
      page = currentPage * pageSize - pageSize
    }
    const recordlist = await db.findRecords(page, pageSize)
    const recordCounts = await db.findRecordCount()
    const recordCount = recordCounts[0].num
    const currentPages = currentPage
    const option = {
      recordlist: recordlist,
      currentPage: currentPages,
      recordtotalPages: Math.ceil(recordCount / pageSize)
    }
    return option
  },

  ToMain: async function () {
    // top10
    const usertoplist = await db.findPrintNumber()
    const dataname = []
    const dataprintnumber = []
    for (let i = 0; i < usertoplist.length; i++) {
      dataname[i] = usertoplist[i].name
      dataprintnumber[i] = usertoplist[i].printNumber
    }
    // 近7日打印次数数据
    const result = await db.findRecordNumbers()
    const date = []
    const number = []
    for (let i = 0; i < result.length; i++) {
      date[i] = result[i].dates
      number[i] = result[i].num
    }
    // 用户总数
    const totolUser = await db.findUserCount()
    // 总打印次数
    const totolPrint = await db.findTotolPrintNumber()

    const option = {
      usertoplistname: dataname,
      usertoplistnumber: dataprintnumber,
      date: date,
      number: number,
      totoluser: totolUser[0].num,
      totolprint: totolPrint[0].totolPrintNumber
    }
    return option
  }

}
module.exports = new Tool()
